
const { app,ipcMain,BrowserWindow } = require('electron')
const mysql = require('mysql')
var stockCfg = require('../../config/stock.json');

var sqlMgr={
  dbcon : null,
  getCon(cb){
    if(this.dbcon) return;
    var connection = mysql.createConnection({
      host     : stockCfg.db.host,
      port     : stockCfg.db.port || 3306,
      user     : stockCfg.db.user,
      password : stockCfg.db.password,
      database : stockCfg.db.database,
      connectTimeout: 1000,
      dateStrings : true,
    });

    connection.connect(function(err){
        if(err){
            console.error('error connection:'+err.stack);
        }
        if(cb){
          cb(err);
        }
        // console.log('connect as id'+connection.threadId);
    });
    // if(connection.threadId){
    //   this.dbcon = connection;
    // }
    // throw new Error("数据库连接失败");
  },
  reCon(cb){
    if(this.dbcon){
      this.dbcon.destory();
    }
    this.dbcon = null;
    this.getCon(cb);
  },
  insertHis(){
    this.getCon();
    var  userAddSql = 'INSERT INTO node_user(id,name,age) VALUES(0,?,?)';
    var  userAddSql_Params = ['Wilson', 55];
    this.dbcon.query(userAddSql,userAddSql_Params,function (err, result) {
      if(err){
        console.log('[INSERT ERROR] - ',err.message);
        return;
      }
      console.log('-------INSERT----------');
      console.log('INSERT ID:',result);       
    });
  }
}



ipcMain.on("reCon",(event)=>{
  try{
    sqlMgr.reCon((err)=>{
      event.sender.send('reConRes', err);
    });
  }catch(ex){
    event.sender.send('reConRes', "数据连接失败:"+ex.message);
  }
});
 


// connection.connect();
 
// connection.query('select * from stock_event limit 10', function (error, results, fields) {
//   debugger;
//   if (error) throw error;
//   console.log('The solution is: ', results[0].solution);
// });


